package com.syni.mdd.sjb.common.datatreaure.controller.protect.minapp;

import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserChannel;
import com.syni.mdd.sjb.common.component.utils.common.annotations.CheckUserIdentity;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusiness.GetBusinessDataByIdDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusiness.GetBusinessDataByIdsDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddUser.apiUser.GetMidongdongUserByPhoneDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddUser.apiUser.GetMidongdongUserDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.commonuser.UserRestService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.BusinessRestService;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultCode;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.controller.BaseController;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.minAppLogin.FastPhoneRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.FastPhoneVo;
import com.syni.mdd.sjb.common.datatreaure.service.DxshAppUserChannelService;
import com.syni.mdd.sjb.common.datatreaure.utils.TokenUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/minApp/login")
@Log4j2
public class LoginController extends BaseController {

    @Autowired
    TokenUtils tokenUtils;

    @Autowired
    UserRestService userRestService;

    @Autowired
    DxshAppUserChannelService dxshAppUserChannelService;

    @Autowired
    BusinessRestService businessRestService;


    @PostMapping("/fastPhone")
    @ApiOperation(value = "微信手机号快捷登陆")
    public Map<String,Object> fastPhone(@RequestBody @Validated FastPhoneVo fastPhoneVo){
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        String userToken = requestHeaderData.getString("logintoken");
        if(!fastPhoneVo.isInternalCall()) {
            if (!tokenUtils.checkDxshMinApp(userToken)) {
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_DXSH_MIN_APP);
            }
        }
        String phone = fastPhoneVo.getPhone();
        RpcResponseVo rpcResponseVo = userRestService.dxshMinAppUserLoginByPhone(phone);
        if(!rpcResponseVo.isSuccess()){
            if(rpcResponseVo.getStatus().equals(ResultCode.CODE_ERROR_05)){
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_ACCOUNT_NO_EXIST);
            }
        }
        Integer isHaveVerPermission = 0;
        GetMidongdongUserByPhoneDto getMidongdongUserByPhoneDto = rpcResponseVo.parseObject(GetMidongdongUserByPhoneDto.class);
        List<DxshAppUserChannel> dxshAppUserChannelList = new ArrayList<>();
        FastPhoneRpVo fastPhoneRpVo = new FastPhoneRpVo();
        fastPhoneRpVo.setToken(getMidongdongUserByPhoneDto.getToken());
        fastPhoneRpVo.setRole(getMidongdongUserByPhoneDto.getRole());

        if(fastPhoneRpVo.getRole() == Constants.MDD_MAN_ROLE_ID){
            dxshAppUserChannelList = dxshAppUserChannelService.getDxshChannelByUserIdAndChannel(getMidongdongUserByPhoneDto.getUserId(),DxshAppUserChannelService.CHANNEL_MDD);
        }else if(fastPhoneRpVo.getRole() == Constants.MDD_DY_ROLE_ID){
            /*if(getMidongdongUserByPhoneDto.getPermissionIds().contains(Constants.VER_PERMISSION)){
                isHaveVerPermission = Constants.COMMON_FLAG_TRUE_INT;
            }*/
            if(getMidongdongUserByPhoneDto.getManagerBusinessId() != null) {
                DxshAppUserChannel dxshAppUserChannel = dxshAppUserChannelService.getDxshChannelByBusinessIdAndChannel(getMidongdongUserByPhoneDto.getManagerBusinessId(),DxshAppUserChannelService.CHANNEL_MDD);
                if(dxshAppUserChannel != null){
                    dxshAppUserChannelList.add(dxshAppUserChannel);
                }
            }
        }
        fastPhoneRpVo.setAssistantName(getMidongdongUserByPhoneDto.getAssistantName());
        //查询店铺信息
        if(CollectionUtils.isNotEmpty(dxshAppUserChannelList)){
            fastPhoneRpVo.setIsHaveBusiness(Constants.COMMON_FLAG_TRUE_INT);
            Map<Integer,GetBusinessDataByIdDto> getBusinessDataByIdDtoMap = new HashMap<>();
            Set<Integer> businessIds = dxshAppUserChannelList.stream().map(DxshAppUserChannel::getBusinessId).collect(Collectors.toSet());
            GetBusinessDataByIdsDto getBusinessDataByIdsDto = new GetBusinessDataByIdsDto();
            getBusinessDataByIdsDto.setBusinessIds(businessIds);
            rpcResponseVo = businessRestService.getBusinessByIds(getBusinessDataByIdsDto);
            if(rpcResponseVo.isSuccess()){
                getBusinessDataByIdsDto = rpcResponseVo.parseObject(GetBusinessDataByIdsDto.class);
                List<GetBusinessDataByIdDto> gts = getBusinessDataByIdsDto.getBusinessData();
                if(CollectionUtils.isNotEmpty(gts)){
                    gts.forEach(gt -> {
                        getBusinessDataByIdDtoMap.put(gt.getId(),gt);
                    });
                }
            }
            for(DxshAppUserChannel dxshAppUserChannel : dxshAppUserChannelList){
                Integer businessIsHaveVerPermission = Constants.COMMON_FLAG_FALSE_INT;
                if(getBusinessDataByIdDtoMap.containsKey(dxshAppUserChannel.getBusinessId())) {
                    if(fastPhoneRpVo.getRole() == Constants.MDD_MAN_ROLE_ID && dxshAppUserChannel.getQualificationStatus() == Constants.COMMON_FLAG_TRUE_INT){
                        businessIsHaveVerPermission = Constants.COMMON_FLAG_TRUE_INT;
                    } else if(fastPhoneRpVo.getRole() == Constants.MDD_DY_ROLE_ID){
                        if(getMidongdongUserByPhoneDto.getPermissionIds().contains(Constants.VER_PERMISSION)){
                            businessIsHaveVerPermission = Constants.COMMON_FLAG_TRUE_INT;
                        }
                    }
                    GetBusinessDataByIdDto getBusinessDataByIdDto = getBusinessDataByIdDtoMap.get(dxshAppUserChannel.getBusinessId());
                    fastPhoneRpVo.getBusinesses().add(FastPhoneRpVo.newBuilderBusinessData().setBusinessName(getBusinessDataByIdDto.getVendorName())
                            .setLogoUrl(getBusinessDataByIdDto.getLogoUrl())
                            .setAddr(getBusinessDataByIdDto.getAddrDetails())
                            .setLatitude(getBusinessDataByIdDto.getLatitude())
                            .setLongitude(getBusinessDataByIdDto.getLongitude())
                            .setIsHaveVerPermission(businessIsHaveVerPermission)
                            .setBusinessId(getBusinessDataByIdDto.getId())
                            .build());
                }
            }
            if(fastPhoneRpVo.getBusinesses().size() > 0){
                //匹配最近的
                FastPhoneRpVo.BusinessData max = null;
                if(StringUtils.isNotBlank(fastPhoneVo.getLongitude()) && StringUtils.isNotBlank(fastPhoneVo.getLatitude())) {
                    Double distanceMax = Double.MAX_VALUE;
                    for (FastPhoneRpVo.BusinessData fg : fastPhoneRpVo.getBusinesses()) {
                        if (StringUtils.isNotBlank(fg.getLatitude()) && StringUtils.isNotBlank(fg.getLongitude())) {
                            Double distance = LocationUtils.getDistance(Double.parseDouble(fastPhoneVo.getLatitude()), Double.parseDouble(fastPhoneVo.getLongitude()),
                                    Double.parseDouble(fg.getLatitude()), Double.parseDouble(fg.getLongitude()));
                            if (distance < distanceMax) {
                                distanceMax = distance;
                                max = fg;
                            }
                        }
                    }
                }
                if(max == null){
                    fastPhoneRpVo.setBusinessName(fastPhoneRpVo.getBusinesses().get(0).getBusinessName());
                    fastPhoneRpVo.setLogoUrl(fastPhoneRpVo.getBusinesses().get(0).getLogoUrl());
                    fastPhoneRpVo.setBusinessId(fastPhoneRpVo.getBusinesses().get(0).getBusinessId());
                    fastPhoneRpVo.setIsHaveVerPermission(fastPhoneRpVo.getBusinesses().get(0).getIsHaveVerPermission());
                }else {
                    fastPhoneRpVo.setBusinessName(max.getBusinessName());
                    fastPhoneRpVo.setLogoUrl(max.getLogoUrl());
                    fastPhoneRpVo.setBusinessId(max.getBusinessId());
                    fastPhoneRpVo.setIsHaveVerPermission(max.getIsHaveVerPermission());
                }
            }
        }
        return ResultMapHelper.success(fastPhoneRpVo,ResultMsg.MSG_GET_SUCCESS);
    }


    @PostMapping("/phoneByVerificationCode")
    @ApiOperation(value = "手机号验证码登陆")
    public Map<String,Object> phoneByVerificationCode(@RequestBody @Validated FastPhoneVo fastPhoneVo){
        String phone = fastPhoneVo.getPhone();
        String verificationCode = fastPhoneVo.getVerificationCode();
        String password = fastPhoneVo.getPassword();
        RpcResponseVo rpcResponseVo;
        if(StringUtils.isNotBlank(password)){
            rpcResponseVo = userRestService.checkDxshUserPwd(phone, password);
            if (!rpcResponseVo.isSuccess()) {
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_ACCOUNT_PWD_ERROR);
            }
        }else {
            rpcResponseVo = userRestService.checkVerificationCode(phone, verificationCode, Constants.DXSH_MINAPP_CODE_TYPE);
        }
        if (!rpcResponseVo.isSuccess()) {
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_ACCOUNT_VER_CODE_ERROR);
        }
        fastPhoneVo.setInternalCall(true);
        return this.fastPhone(fastPhoneVo);
    }

    @PostMapping("/repeatLoading")
    @ApiOperation(value = "刷新首页")
    @CheckUserIdentity
    public Map<String,Object> repeatLoading(@RequestBody @Validated FastPhoneVo fastPhoneVo){
        GetMidongdongUserDto getMidongdongUserDto = new GetMidongdongUserDto();
        getMidongdongUserDto.setUserId(fastPhoneVo.getUserId());
        RpcResponseVo rpcResponseVo = userRestService.getMidongdongUser(getMidongdongUserDto);
        if(!rpcResponseVo.isSuccess()){
            return ResultMapHelper.result(ResultCode.CODE_ERROR,ResultMsg.HAND_FAIL);
        }
        getMidongdongUserDto = rpcResponseVo.parseObject(GetMidongdongUserDto.class);
        if(StringUtils.isBlank(getMidongdongUserDto.getPhone())){
            return ResultMapHelper.result(ResultCode.CODE_ERROR,ResultMsg.HAND_FAIL);
        }
        fastPhoneVo.setPhone(getMidongdongUserDto.getPhone());
        fastPhoneVo.setInternalCall(true);
        return this.fastPhone(fastPhoneVo);
    }

    @PostMapping("/noSql")
    @ApiOperation(value = "刷新首页")
    public Map<String,Object> noSql(@RequestBody @Validated FastPhoneVo fastPhoneVo){
        return ResultMapHelper.success(null,ResultMsg.MSG_GET_SUCCESS);
    }


    @PostMapping("/haveSql")
    @ApiOperation(value = "刷新首页")
    public Map<String,Object> haveSql(@RequestBody @Validated FastPhoneVo fastPhoneVo){
        List<DxshAppUserChannel> dxshAppUserChannels = dxshAppUserChannelService.list();
        dxshAppUserChannels = dxshAppUserChannels.subList(0,5);
        return ResultMapHelper.success(dxshAppUserChannels,ResultMsg.MSG_GET_SUCCESS);
    }

    @PostMapping("/haveSqlSys")
    @ApiOperation(value = "刷新首页")
    public Map<String,Object> haveSqlSys(@RequestBody @Validated FastPhoneVo fastPhoneVo){
        List<DxshAppUserChannel> dxshAppUserChannels = dxshAppUserChannelService.list();
        log.info("haveSqlSys size：" + dxshAppUserChannels.size());
        return ResultMapHelper.success(null,ResultMsg.MSG_GET_SUCCESS);
    }

}
